import { ref } from "vue";

export const useTimer = (time = 60, startMsg = "发送验证码",endMsg = '重新发送') => {
  const cur = ref(time);
  let timer = null;
  let msg = ref(startMsg);
  const initData = () => {
    timer = null
    cur.value = time
  }
  function changeTimer() {
    if (timer) return;
    timer = setInterval(() => {
      if (cur.value <= 0) {
        clearInterval(timer);
        initData()
        msg.value = endMsg
      } else {
        cur.value--;
        msg.value = cur.value + 's'
      }
    }, 1000);
  }
  
  return {
    cur,
    msg,
    changeTimer,
  };
};
